package com.live.dengdengtv.activity.login;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.live.dengdengtv.CustomTitleActivity;
import com.live.dengdengtv.R;
import com.live.dengdengtv.activity.MainHallActivity;
import com.live.dengdengtv.activity.support.LoginHelper;
import com.live.dengdengtv.bean.AppConstants;
import com.live.dengdengtv.bean.AppInfo;
import com.live.dengdengtv.bean.LoginInfo;
import com.live.dengdengtv.bean.SimpleInfoData;
import com.live.dengdengtv.bean.gson.GUserInfo;
import com.live.dengdengtv.activity.support.ProfileInfoHelper;
import com.live.dengdengtv.kernel.presenters.viewinface.LoginView;
import com.live.dengdengtv.net.NetTaskList;
import com.live.dengdengtv.utils.Lo;
import com.live.dengdengtv.utils.Notice;
import com.live.dengdengtv.utils.ViewClickUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends CustomTitleActivity implements LoginView {

    private static final String TAG =  LoginActivity.class.getName();

    private EditText phone_et;
    private EditText password_et;

    private LoginHelper mLoginHeloper;
    private ProfileInfoHelper mUserInfoHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login, R.layout.title_custom_red);
        setDefaultTitle("手机登陆");
        setRightText("注册");
        title_left_iv.setVisibility(View.INVISIBLE);


        mLoginHeloper = new LoginHelper(this, this);
        mUserInfoHelper = new ProfileInfoHelper(null);

        phone_et = (EditText) findViewById(R.id.phone_et);
        password_et = (EditText) findViewById(R.id.password_et);

        initView();

        Button sign_in = (Button) findViewById(R.id.next_bt);
        sign_in.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(ViewClickUtils.isFastClick(2000)){
                    return;
                }
                String phone = phone_et.getText().toString().trim();
                String password = password_et.getText().toString().trim();

                if(TextUtils.isEmpty(phone) || TextUtils.isEmpty(password)){
                    Notice.alert(context, "用户名或密码不能为空!");
                    return;
                }
                attemptLogin();

            }
        });
    }

    private void initView() {
        SharedPreferences sp = context.getSharedPreferences(AppConstants.SP_LOGIN, Context.MODE_PRIVATE);
        String phone = sp.getString("userPhone","");
        String password = sp.getString("userPassword","");

        phone_et.setText(phone);
        password_et.setText(password);
    }

    private void attemptLogin(){
        Map<String,String> params = new HashMap<String, String>();
        params.put("phone", phone_et.getText().toString().trim());
        params.put("password", password_et.getText().toString().trim());
        params.putAll(AppInfo.getHeadInfo());
        requestData(NetTaskList.login, params,0);
    }
    @Override
    public void loginSucc() {
        getMyInfo();
    }
    @Override
    public void loginFail() {
        Notice.alert(context, "网络错误!");
    }

    private void getMyInfo(){
        requestData(NetTaskList.get_userInfo, AppInfo.getHeadInfo(),1);
    }
    private void getRoomId(){
        NetTaskList.getInstance().getRoomId(this, 2, this);
    }

    private void getBannerList(){
        requestData(NetTaskList.get_bannerList, AppInfo.getHeadInfo(),1001);
    }

    @Override
    public boolean onResponse(SimpleInfoData response, int id) {
        if (response.result == 0) {
            if (id == 0) {
                JsonObject dataJson = response.data.getAsJsonObject();
                AppInfo.loginInfo.setUserId(dataJson.get("user_id").getAsString());
                AppInfo.loginInfo.setUserSig(dataJson.get("user_sign").getAsString());
                AppInfo.loginInfo.setUserPhone(phone_et.getText().toString().trim());
                AppInfo.loginInfo.setUserPassword(password_et.getText().toString().trim());
                AppInfo.loginInfo.holdLoginInfo(context);

                mLoginHeloper.imLogin(LoginInfo.getInstance().getUserId(), LoginInfo.getInstance().getUserSig());
            } else if (id == 1) {
                GUserInfo userInfo = new Gson().fromJson(response.data.getAsJsonObject(), GUserInfo.class);
                Log.e("onResponse", userInfo.toString());
                LoginInfo.getInstance().setgUserInfo(userInfo);

                mUserInfoHelper.setMyNickName(LoginInfo.getInstance().getUserNickname());
                mUserInfoHelper.setMySex(LoginInfo.getInstance().getUserSex());
                mUserInfoHelper.setMyAvator(LoginInfo.getInstance().getAvatarAddress());
                mUserInfoHelper.setMySign(LoginInfo.getInstance().getUserSign());

                getRoomId();

            } else if (id == 2) {
                int room_id = response.data.getAsJsonObject().get("room_id").getAsInt();
                Log.e("room_id", room_id + "");
                LoginInfo.getInstance().setRoomId(room_id);
                LoginInfo.getInstance().setChatRoomId(room_id + "");
                jumpIntoHomeActivity();
            } else if (id == 1001) {
                JsonArray array = response.data.getAsJsonArray();
                List<String> bannerList = new ArrayList<>();
                for (int i = 0; i < array.size(); i++) {
                    bannerList.add(array.get(i).getAsJsonObject().get("advert_url").toString());
                }
                LoginInfo.getInstance().setBannerList(bannerList);
            }
        }

        return false;
    }


    public void verifyLogin(View view) {

        Lo.e("verifyLogin");
        Intent intent = new Intent(context, LoginMessageActivity.class);
        startActivity(intent);

    }

    public void forgetPassword(View view) {

        Lo.e("forgetPassword");
        Intent intent = new Intent(context, ForgetPwordActivity.class);
        startActivity(intent);

    }

    /**
     * 直接跳转主界面
     */
    private void jumpIntoHomeActivity() {

        Intent intent = new Intent(LoginActivity.this, MainHallActivity.class);
        startActivity(intent);

        setJPush();
    }

    private void setJPush(){

        JPushInterface.setDebugMode(false);
        JPushInterface.init(this);

        CustomPushNotificationBuilder builder =
                new CustomPushNotificationBuilder(
                        this,
                        R.layout.customer_notitfication_layout,
                        R.id.icon, R.id.title, R.id.text);
        builder.layoutIconDrawable = R.mipmap.ic_logo;
        builder.statusBarDrawable  = R.mipmap.ic_logo;
//        builder.developerArg0 = "developerArg2";
        JPushInterface.setDefaultPushNotificationBuilder( builder);
    }


    @Override
    protected void onRightTextViewClick(View v){
        goRegisterAct();
    }

    private void goRegisterAct(){
        Intent intent = new Intent(context, RegisterActivity.class);
        startActivity(intent);
    }



}

